/**
@author		Jong Min, Lee
@date		  10/01/2014
@breif		instance class 

copyright(c) Tae Young Soft. All right reserved. 2014
*/
#include "stdafx.h"
#include "Taurus_DcmData/Instance.h"

#include "Taurus_DcmData/DcmInstance.h"
#include "Taurus_DcmData/Series.h"
#include "Taurus_DcmData/Frame.h"

CInstance::CInstance()
{
  init();
}

CInstance::~CInstance()
{
  destroy();
}

const TCHAR* CInstance::getSOPClassUID() const
{
  return m_theDcmInstance->getSOPClassUID();
}

void CInstance::init()
{
  m_theParent = NULL;

  m_theDcmInstance = NULL;
}

void CInstance::destroy()
{
  m_theDcmInstance->decreaseRefCount();
  
  removeAllFrames();
}

void CInstance::removeAllFrames()
{
  unsigned int numFrames = m_theFrames.size();
  for(unsigned int i = 0; i < numFrames; ++i)
    _DELETE(m_theFrames[i]);
  m_theFrames.clear();
}

DWORD CInstanceProducer::produce(CDcmInstance* dcmInstance, 
                                 CSeries* parent, 
                                 CInstance*& outInstance)
{
  if(dcmInstance == NULL) return ERROR_INVALID_PARAMETER;

  CInstance* newInstance = NULL;
  _TRY_ALLOC(newInstance, CInstance)
  if(newInstance == NULL) return ERROR_NOT_ENOUGH_MEMORY;

  DWORD error = ERROR_SUCCESS;
  
  newInstance->m_theParent = parent;
  newInstance->m_theDcmInstance = dcmInstance;
  newInstance->m_theDcmInstance->increaseRefCount();

  unsigned int numFrames = dcmInstance->getNumFrames();
  if(numFrames == 0) return ERROR_SUCCESS;

  _TRY_BEGIN
  newInstance->m_theFrames.reserve(numFrames);
  _CATCH_ALL
  _DELETE(newInstance)
  return ERROR_NOT_ENOUGH_MEMORY;
  _CATCH_END

  for(unsigned int i = 0; i < numFrames; ++i)
  {
    CDcmFrame* dcmFrame = dcmInstance->getFrame(i);
    if(dcmFrame == NULL) continue;

    CFrame* newFrame = NULL;
    error = CFrameProducer::produce(dcmFrame,
                                    newInstance,
                                    newFrame);
    if(error != ERROR_SUCCESS)
    {
      _DELETE(newInstance)
      return error;
    }

    newInstance->m_theFrames.push_back(newFrame);
  }

  outInstance = newInstance;
  return ERROR_SUCCESS;
}

  
